package fieldmaps.mapalgebra.unaryOperations;

import java.sql.SQLException;
import java.util.NoSuchElementException;

import org.apache.log4j.Logger;

import com.vividsolutions.jts.geom.Polygon;

import fieldmaps.database.DatabaseGenericMap;
import fieldmaps.database.DatabaseRasterMap;
import fieldmaps.types.MapInfo;

public class RasterUnaryMapAlgebra {
	private static Logger LOGGER = Logger.getLogger(RasterUnaryMapAlgebra.class);
	
	private DatabaseRasterMap map;
	
	public RasterUnaryMapAlgebra(String mapName) {
		if (mapName == null || mapName.isEmpty()) {
			throw new IllegalArgumentException("Wrong map name!");
		}
		
		map = DatabaseRasterMap.loadMap(mapName);
	}
	
	public DatabaseGenericMap mapOperation (ICallbackUnary callbackObject) {
		Polygon polygon;
		MapInfo mapInfo = new MapInfo(map.getMapInfo());
		DatabaseRasterMap newMap = DatabaseRasterMap.createMap(mapInfo, callbackObject.newMapName());
		
		map.startCellIteration();
		try {
			while ((polygon = map.getNextCell()) != null) {
				Integer userData = (Integer) callbackObject.doOperation(polygon.getUserData());
				newMap.addCell(polygon.getCoordinates(), userData);
			}
		} catch (NoSuchElementException e) {
			LOGGER.info("New map: " + callbackObject.newMapName() + " successfully created!");
			return newMap;
		} catch (SQLException e) {
			LOGGER.error(e.getMessage());
		}
		map.resetCellIteration();
		return null;
	}
}
